<?php

namespace App\Logic\Admin;

use App\Constants\ErrorCode;
use App\Utils\MD5Token;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use function Hyperf\Support\env;
class AdministratorLogic
{
    #[Inject]
    protected MD5Token $md5Token;
    #[Inject]
    protected ValidatorFactoryInterface $validationFactory;
    /**
     * Notes:获取当前管理员信息
     * 2025/7/9
     * @param array $user
     * @return array
     * @throws \Exception
     */
    public function administrator(array $user): array
    {
        if (empty($user)) {
            throw new \Exception(ErrorCode::getMessage(ErrorCode::TOKEN_INVALID), ErrorCode::TOKEN_INVALID);
        }
        if (isset($user['mobile'])&&!empty($user['mobile'])){//手机号脱敏
            $user['mobile'] = maskMobile($user['mobile']);
        }
        return $user;
    }

    /**
     * Notes:管理员列表
     * 2025/7/15
     * @param $params
     * @return \Hyperf\Contract\LengthAwarePaginatorInterface
     */
    public function list($params)
    {
        $query = \App\Model\Administrator::query();
        if (isset($params['name']) && trim($params['name']) != '') {
            $query->where('name', 'like', '%' . $params['name'] . '%');
        }

        if (isset($params['email']) && trim($params['email']) != '') {
            $query->where('email', $params['email']);
        }

        $limit = (int) $params['limit'] ?? 20;
        if (isset($params['sort']) && $params['sort'] == '-id') {
            $query->orderByDesc('id');
        }

        if (isset($params['sort']) && $params['sort'] == '+id') {
            $query->orderBy('id');
        }
        $list = $query->orderByDesc('login_at')->with('roles')->paginate($limit);
        return $list;
    }

    /**
     * Notes:退出登录
     * 2025/7/17
     * @param string $token
     * @return array
     * @throws \RedisException
     */
    public function logout(string $token): array
    {
        $this->md5Token->revokeToken($token);
        return [];
    }

    /**
     * Note:获取管理员的信息
     * User: Kong
     * Date: 2025/9/25
     * Time: 15:24
     * @param $data
     * @return array|mixed[]
     * @throws \Exception
     */
    public function getAdministratorInfo($data)
    {
        try {
            $id = $data['id']??0;
            if ($id<=0){
                throw new \Exception("请选择管理员");
            }
            $administrator = \App\Model\Administrator::query()->with('roles')->find($id);
            if (! $administrator) {
                throw new \Exception('未找到信息', 404);
            }
            return $administrator->toArray();
        } catch (\Throwable $exception) {
            throw new \Exception($exception->getMessage());
        }
    }
    /**
     * Note:获取当前管理员的信息
     * User: Kong
     * Date: 2025/9/25
     * Time: 14:54
     * @param $token
     * @return mixed
     * @throws \RedisException
     */
    public function getCurrentAdministratorInfo($token)
    {
        $admin = $this->md5Token->verifyToken($token);
        $account = \App\Model\Administrator::with('roles')
            ->where('id', $admin['id'])
            ->first();
        if (!$account) {
            throw new \Exception('用户不存在');
        }
        $roles = [];
        foreach ($account->roles as $role) {
            $roles[] = $role->role_key;
        }
        if ($account->status == \App\Model\Administrator::FORBID_STATUS) {
            throw new \Exception('此用户禁止登录');
        }
        return $account;
    }

    /**
     * Note:创建管理员
     * User: Kong
     * Date: 2025/9/25
     * Time: 15:05
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public function create($data)
    {
        $validator = $this->validationFactory->make(
            $data,
            [
                'name' => 'required',
                'email' => 'required|email',
                'password' => 'required|min:6',
                're_password' => 'required|same:password',
            ],
            [
                'name.*' => '名称必填',
                'email.*' => '无效的邮箱',
                'password.required' => '密码必填',
                'password.min' => '密码的长度不能小于 6 位',
                're_password.*' => '两次密码不一致',
            ]
        );
        if ($validator->fails()) {
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new \Exception($errorMessage);
        }
        $user = \App\Service\Admin\AdministratorService::createAdministrator($data);
        return $user;
    }

    /**
     * Note:修改管理员信息
     * User: Kong
     * Date: 2025/9/25
     * Time: 15:06
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public function update($data)
    {
        $administrator = \App\Service\Admin\AdministratorService::updateAdministratorById($data);
        return $administrator;
    }

    /**
     * Note:修改管理员密码
     * User: Kong
     * Date: 2025/9/25
     * Time: 15:13
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public function updatePassword($data): array
    {
        try {
            $validation = $this->validationFactory->make(
                $data,
                [
                    'uid' => 'required|min:1',
                    'password' => 'required|min:6',
                    're_password' => 'required|same:password',
                ],
                [
                    'password.required' => '密码不能为空',
                    'password.min' => '密码至少长度不能小于 6',
                    'uid.required' => '请选择管理员',
                    'uid.min' => '请选择管理员',
                    're_password.required' => '重复密码不能为空',
                    're_password.same' => '两次密码不一致',
                ]
            );
            if ($validation->fails()) {
                throw new \Exception($validation->errors()->first());
            }
            $id = $data['uid'];
            $administrator = \App\Model\Administrator::query()->find($id);
            if (! $administrator) {
                throw new \Exception('未找到用户');
            }

            $administrator->password = password_hash($data['password'], PASSWORD_DEFAULT);
            $rt = $administrator->save();
            if (! $rt) {
                throw new \Exception('修改密码失败');
            }
            return [];
        } catch (\Throwable $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * Note:封禁用户
     * User: Kong
     * Date: 2025/9/25
     * Time: 15:17
     * @param $data
     * @return array
     * @throws \Exception
     */
    public function forbid($data)
    {
        try {
            $id = $data['id']??0;
            if ($id<=0){
                throw new \Exception('请选择用户');
            }
            if (env('ADMINISTRATOR_ID', 1) == $id) {
                throw new \Exception('此账户不能封禁');
            }
            $admin = \App\Model\Administrator::query()->find($id);
            if (! $admin) {
                throw new \Exception('未找到用户');
            }
            if ($admin->status == \App\Model\Administrator::NORMAL_STATUS) {
                $admin->status = \App\Model\Administrator::FORBID_STATUS;
            } else {
                $admin->status = \App\Model\Administrator::NORMAL_STATUS;
            }

            $admin->save();
            return [];
        } catch (\Throwable $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * Note:删除用户
     * User: Kong
     * Date: 2025/9/25
     * Time: 15:19
     * @param $data
     * @return array
     * @throws \Exception
     */
    public function destroy($data)
    {
        try {
            $id = $data['id']??0;
            if ($id<=0){
                throw new \Exception('请选择用户');
            }
            if (env('ADMINISTRATOR_ID', 1) == $id) {
                throw new \Exception('此账户不能删除');
            }
            $admin = \App\Model\Administrator::query()->find($id);
            if (! $admin) {
                throw new \Exception('未找到用户');
            }
            $rt = $admin->delete();
            if (!$rt){
                throw new \Exception("删除失败");
            }
            return [];
        } catch (\Throwable $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * Note:设置管理员的角色
     * User: Kong
     * Date: 2025/9/25
     * Time: 15:20
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public function setAdminRole($data)
    {
        try {
            $validate = $this->validationFactory->make(
                $data,
                [
                    'administrator_id' => 'required',
                    'role_id' => 'required',
                ],
                [
                    'administrator_id.*' => 'administrator_id is required',
                    'role_id.*' => 'role_id is required',
                ]
            );
            if ($validate->fails()) {
                throw new \Exception($validate->getMessageBag()->first());
            }
            $result = \App\Service\Admin\AdministratorService::setAdminRole($data['administrator_id'], $data['role_id']);
            return $result;
        } catch (\Throwable $exception) {
            throw new \Exception($exception->getMessage());
        }
    }
}